<template>
  <div>
    <my-breadcrumb :items="['员工管理', '员工权限']"></my-breadcrumb>
    <div>
      <Row :gutter="24">
        <i-col span="6">
          <div class="roles">
            <div class="title">所有角色</div>
            <div class="content">
              <ul>
                <li style="margin-top: 10px;text-align: center;border-top: none;"><Button icon="plus" @click="addBtn">添加角色</Button></li>
                <li v-for="(role, index) in officialRole" :key="index" @click="clickRole(role, 1)" class="official_li">
                  <h3>
                    {{role.name}}
                    <span class="official">官方</span>
                  </h3>
                  <p>{{role.description}}</p>
                  <p class="warning">官方角色，可直接使用，不可修改，不可删除</p>
                </li>
                <li v-for="(role, index) in roles" :key="index" @click="clickRole(role)">
                  <h3>{{role.name}}</h3>
                  <p>{{role.description}}</p>
                  <p style="float: right;cursor: pointer;" @click="deleteRole(role.id)">删除</p>
                </li>
              </ul>
            </div>
          </div>
        </i-col>
        <i-col span="18">
          <div v-show="addShow">
            <Form :model="addRole" :label-width="60" inline>
              <FormItem label="角色名" prop="name">
                <Input v-model="addRole.name" :disabled="isOfficial"/>
              </FormItem>
              <FormItem label="描述" prop="description">
                <Input v-model="addRole.description" :disabled="isOfficial" type="textarea" :autosize="{minRows: 2, maxRows: 5}" style="width: 350px;"/>
              </FormItem>
            </Form>
          </div>
          <div class="permission">
            <div class="title">所有权限</div>
            <div class="content tree">
              <Tree :data="treeData" show-checkbox ref="tree" @on-check-change="checkChange"></Tree>
              <div v-if="addShow" style="margin-top: 18px;text-align: center;">
                <Button type="primary" @click="updateRoleSub" v-if="updateBtn" :disabled="isOfficial">修改</Button>
                <Button type="primary" @click="addRoleSub" v-else>添加</Button>
              </div>
            </div>
          </div>
        </i-col>
      </Row>
    </div>
  </div>
</template>

<script>
export default {
  name: 'roles',
  data () {
    return {
      url: {
        list: '/admin/manager/permission/branch/set/list',
        roleAdd: '/admin/manager/permission/branch/role/add',
        roleList: '/admin/manager/permission/role/list',
        roleUpdate: '/admin/manager/permission/branch/role/update',
        rolePermission: '/admin/manager/permission/role/permission/ids',
        roleDelete: '/admin/manager/permission/role/delete'
      },
      roles: [],
      treeData: [],
      addRole: {
        name: '',
        description: ''
      },
      addShow: false,
      updateBtn: false,
      oldNodeIds: [],
      oldRole: '',
      nodeChange: false,
      activeId: null,

      isOfficial: false
    }
  },
  methods: {
    addBtn () {
      this.addShow = true
      this.updateBtn = false
    },
    addRoleSub () {
      if (this.addRole.name !== '') {
        let adds = []
        this.$refs.tree.getCheckedNodes().forEach(item => {
          if (!item.children) {
            adds.push(item.id)
          }
        })
        if (this.addRole.description === '') {
          this.addRole.description = '无'
        }
        let params = {
          userRole: this.addRole,
          adds
        }
        if (adds[0]) {
          params.addPermission = true
        }
        this.$ajax.post(this.url.roleAdd, params)
          .then(res => {
            if (res.data.success) {
              this.initRoles()
              this.$Message.success('添加成功')
            }
          })
      } else {
        this.$Message.error('角色名不能为空')
      }
    },

    clickRole (role, i) {
      if (i) {
        this.isOfficial = true
      } else {
        this.isOfficial = false
      }
      if (this.activeId === role.id) {
        return
      }
      this.activeId = role.id
      this.addShow = true
      this.updateBtn = true
      this.addRole.description = role.description
      this.addRole.name = role.name
      this.oldRole = JSON.stringify(this.addRole)
      this.getRolePermission(role.id)
    },

    getRolePermission (id) {
      this.$ajax.post(this.url.rolePermission, id)
        .then(res => {
          if (res.data.success) {
            this.initTree(res.data.data)
            this.oldNodeIds = res.data.data
          }
        })
    },

    checkChange () {
      this.nodeChange = true
    },

    updateRoleSub () {
      if (this.nodeChange || (JSON.stringify(this.addRole) !== this.oldRole)) {
        let params = {
          userRole: {}
        }
        if (this.nodeChange) {
          let nowNodeIds = []
          this.$refs.tree.getCheckedNodes().forEach(item => {
            if (!item.children) {
              nowNodeIds.push(item.id)
            }
          })
          let oldNodeIds = JSON.parse(JSON.stringify(this.oldNodeIds))
          for (let i = 0; i < nowNodeIds.length; i++) {
            let j = oldNodeIds.indexOf(nowNodeIds[i])
            if (j !== -1) {
              nowNodeIds.splice(i, 1)
              oldNodeIds.splice(j, 1)
              i--
            }
          }
          params.adds = nowNodeIds
          params.removes = oldNodeIds
          if (nowNodeIds[0] || oldNodeIds[0]) {
            params.updatePermission = true
          }
        }
        if (JSON.stringify(this.addRole) !== this.oldRole) {
          params.updateRole = true
          params.userRole = JSON.parse(JSON.stringify(this.addRole))
        }
        params.userRole.id = this.activeId
        if (params.updatePermission || params.updateRole) {
          this.$ajax.post(this.url.roleUpdate, params)
            .then(res => {
              if (res.data.success) {
                this.$Message.success('更新成功')
                this.getRolePermission(this.activeId)
              }
            })
        }
      }
    },

    deleteRole (id) {
      let _self = this
      this.$Modal.confirm({
        title: '确认删除吗？',
        content: '删除角色',
        onOk: () => {
          _self.deleteOk(id)
        }
      })
    },
    deleteOk (id) {
      this.$ajax.post(this.url.roleDelete, id)
        .then(res => {
          if (res.data.success) {
            this.initRoles()
            this.$Message.success('删除成功')
          }
        })
    },

    initTree (arr) {
      this.$ajax.post(this.url.list)
        .then(res => {
          if (res.data.success) {
            this.treeData = []
            let temp = []
            res.data.data.sets.forEach(item => {
              item.title = item.name
              item.children = []
              item.expand = true
              temp['P' + item.id] = item
            })
            let unBind = []
            let cantCheck = false
            res.data.data.childrens.forEach(item => {
              item.title = item.name
              if (arr && arr.indexOf(item.id) !== -1) {
                item.checked = true
              }
              if (item.permissionSetId) {
                if (item.isSensitive === 1 || this.isOfficial) {
                  item.disableCheckbox = true
                  temp['P' + item.permissionSetId].disableCheckbox = true
                }
                temp['P' + item.permissionSetId].children.push(item)
              } else {
                unBind.push(item)
                if (item.isSensitive === 1 || this.isOfficial) {
                  item.disableCheckbox = true
                  cantCheck = true
                }
              }
            })
            for (let i in temp) {
              this.treeData.push(temp[i])
            }
            if (unBind[0]) {
              this.treeData.push({
                title: '未关联权限',
                children: unBind,
                expand: true,
                disableCheckbox: cantCheck
              })
            }
          }
        })
    },
    initRoles () {
      this.roles = []
      this.officialRole = []
      this.$ajax.post(this.url.roleList)
        .then(res => {
          if (res.data.success) {
            res.data.data.forEach(item => {
              if (item.type === 1) {
                this.roles.push(item)
              } else {
                this.officialRole.push(item)
              }
            })
          }
        })
    }
  },
  created () {
    this.initTree()
    this.initRoles()
  }
}
</script>

<style scoped>
  .roles{
    min-width: 240px;
  }
.title{
  height: 35px;
  line-height: 35px;
  background-color: #bbbec4;
  padding-left: 18px;
  border-radius: 5px 5px 0 0;
}
  .content{
    box-sizing: border-box;
    border: 1px solid #dddee1;
  }
  .content li{
    padding: 16px;
    border-top: 1px solid #dddee1;
  }
  .tree{
    padding: 10px;
  }
  .official{
    border: 1px solid #ed3f14;
    padding: 2px;
    font-size: 12px;
    font-weight: 700;
    color: #ed3f14;
  }
  .warning{
    display: none;
    color: #ed3f14;
  }
  .official_li:hover .warning{
    display: inline-block;
  }
</style>
